﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using TruyenTranhCrawler.Utils;
using log4net;

namespace TruyenTranhCrawler.Data
{
    [Table]
    public class Content : BaseObject
    {
        public static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public Content()
        {
            CreatedDate = DateTime.Now;
        }

        [Column(IsPrimaryKey = true, IsDbGenerated = true)]
        public int Content_ID { get; set; }

        [Column]
        public int Book_ID { get; set; }

        [Column]
        public int Chapter { get; set; }

        [Column]
        public string Title { get; set; }
        [Column]
        public string SafeName { get; set; }
        [Column]
        public string SafeNameBook { get; set; }

        [Column]
        public string CrawlUrl { get; set; }
        [Column]
        public string CrawlName { get; set; }

        [Column]
        public bool Finish { get; set; }
        [Column]
        public bool Broken { get; set; }

        [Column]
        public DateTime CreatedDate { get; set; }

        public string Body { get; set; }

        public override void Save()
        {
            Title = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(Title.ToLower()).Trim();
            SafeName = GetSafeName(Title);
            Finish = Body.Length > 0;

            base.Save();
            if(Content_ID==0)
            {
                //ghi thong tin bi loi ra day
                Logger.Error(string.Format("Title: {0},SafeName: {1}, SafeNameBook: {2},CrawlName:{3},CrawlUrl:{4}",
                    Title.Length, SafeName.Length, (SafeNameBook ?? "").Length, CrawlName.Length, CrawlUrl.Length));
            }
            else if (Content_ID > 0 && Finish)
            {
                SetBody(Book_ID, Content_ID, Body);
                var bodyMobile = ConvertToMobileBody(Body);
                SetBodyMobile(Book_ID, Content_ID, bodyMobile);
            }
        }

        /// <summary>
        /// Lay danh sach chap chua co noi dung (chua finish)
        /// </summary>
        /// <returns></returns>
        public static List<Content> GetEmpties()
        {
            using (var context = new CmsDataContext())
            {
                return context.Contents.Where(x => !x.Finish && !x.Broken).ToList();
            }
        }

        /// <summary>
        /// Lấy tất cả chương
        /// </summary>
        /// <returns></returns>
        public static List<Content> FindByBook(int bookId)
        {
            using (var context = new CmsDataContext())
            {
                return context.Contents.Where(x => x.Book_ID == bookId).OrderBy(x => x.Chapter).ToList();
            }
        }

        public static string ConvertToMobileBody(string body, int mobileWidth = 480)
        {
            return "";
//            var newbody = body;
//            var listImgSrc = GetImageSources(newbody);
//            foreach (string s in listImgSrc)
//            {
//                //check if exist 
//                var mobipath = Book.RenderImage(s, mobileWidth);
//                if (string.IsNullOrEmpty(mobipath))
//                {
//                    mobipath = Book.RenderImage(s, mobileWidth);
//                }
//                if (mobipath.Length > 0 && !mobipath.Equals(s))
//                {
//                    var i = newbody.IndexOf(s);
//                    while (i >= 0)
//                    {
//                        newbody = newbody.Substring(0, i) + mobipath + newbody.Substring(i + s.Length);
//                        i = newbody.IndexOf(s, i + mobipath.Length - 1);
//                    }
//                }
//            }
//            return newbody;
        }
        static ArrayList GetImageSources(string sContent)
        {
            var list = new ArrayList();
            var parser = new HtmlParser();
            sContent = parser.Replace(sContent, HtmlParser.Patterns.BREAK, "");
            var imgs = parser.GetContentInNode(sContent, "<img ", ">");
            foreach (var img in imgs)
            {
                var srcs = parser.GetProperty(img, "src");
                if (srcs.Count > 0)
                {
                    var s = srcs[0].Groups[4].Value;
                    var icheck = s.IndexOf("<");
                    if (icheck > 0)
                    {
                        s = s.Substring(0, icheck);
                    }
                    list.Add(s);
                }
            }
            return list;
        }

        public static bool IsNotExisted(int bookId, string crawlUrl)
        {
            using (var context = new CmsDataContext())
            {
                return context.Contents.Count(x => x.Book_ID == bookId && x.CrawlUrl == crawlUrl) <= 0;
            }
        }

        #region Process Body
        public const string FolderPathFormat = "HtmlCache/ContentView/Book{0}/";
        public const string FilePathFormat = "HtmlCache/ContentView/Book{0}/Content{1}.html";
        public const string FilePathFormatMobile = "HtmlCache/ContentView/Book{0}/Content_m{1}.html";
        /// <summary>
        /// Write data to file.
        /// </summary>
        public static void SetBody(int bookId, int contentId, string body)
        {
            if (!string.IsNullOrEmpty(body))
            {
                //write to file
                var folder = Config.PhysicalStaticFile + string.Format(FolderPathFormat, bookId);
                var path = Config.PhysicalStaticFile + string.Format(FilePathFormat, bookId, contentId);
                if (!Directory.Exists(folder))
                    Directory.CreateDirectory(folder);
                using (var w = new StreamWriter(path, false))
                {
                    w.WriteLine(body);
                }
            }
        }

        /// <summary>
        /// Write data to file.
        /// </summary>
        public static void SetBodyMobile(int bookId, int contentId, string body)
        {
//            if (!string.IsNullOrEmpty(body))
//            {
//                //write to file
//                var folder = Config.PhysicalStaticFile + string.Format(FolderPathFormat, bookId);
//                var path = Config.PhysicalStaticFile + string.Format(FilePathFormatMobile, bookId, contentId);
//                if (!Directory.Exists(folder))
//                    Directory.CreateDirectory(folder);
//                using (var w = new StreamWriter(path, false))
//                {
//                    w.WriteLine(body);
//                }
//            }
        }
        #endregion
    }

}
